package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: xrl
 * @Date: 2022/10/13  11:36
 * @Version 1.0
 * 自媒体微服务使用拦截器获取到header中的的用户信息，并放入到threadlocal中
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    /**
     * 前置处理    获取用户信息，存入线程中
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取登录用户的id
        String userId = request.getHeader("userId");
        //排除登录请求
        String path = request.getRequestURI().toString();
        if (path.contains("/in")) {
            return true;
        }

//        if (path.contains("/sensitive")) {
//            return true;
//        }

        //判断userId是否存在
        if (StringUtils.isBlank(userId)) {
            log.error("当前用户没有登录,请求被禁止");
            return false;
        }

        //userId不为空
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        //将用户id设置到线程中
        WmThreadLocalUtil.setUser(wmUser);
        return true;
    }

    /**
       * 后置处理，清理threadlocal中的数据，防止内存溢出
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.delete();
    }
}
